package product_logic

import (
	"strings"
	"wx-uniapp-go/internal/repository/dto"
	"wx-uniapp-go/internal/repository/models"
	"wx-uniapp-go/third_party/oss"
)

// ListComment 获取商品评价列表
func (l *ProductLogic) ListComment(req *dto.ListCommentReq) (*dto.ListCommentResp, error) {
	where := "product_id = ? AND status = ?"
	var params []interface{}
	params = append(params, req.ProductId, 1) // 只查询显示状态的评价

	// 评分筛选
	if req.Score > 0 {
		where += " AND score = ?"
		params = append(params, req.Score)
	}

	// 获取评价列表
	var comments []*models.ProductComment
	count, err := models.FindByPage(l.Ctx, &comments, req.Page, req.PageSize, where, params...)
	if err != nil {
		return nil, err
	}

	// 获取用户信息
	userIds := make([]int64, 0, len(comments))
	for _, comment := range comments {
		userIds = append(userIds, comment.UserId)
	}
	users, err := models.UserFindByIds(l.Ctx, userIds)
	if err != nil {
		return nil, err
	}

	// 构建用户映射
	userMap := make(map[int64]*models.User)
	for _, user := range users {
		userMap[user.Id] = user
	}

	// 转换响应
	list := make([]dto.CommentItem, len(comments))
	for i, comment := range comments {
		// 处理图片路径
		images := make([]string, len(comment.Images))
		for j, img := range comment.Images {
			images[j] = oss.Cli.JoinPath(img)
		}

		// 获取用户信息
		user := userMap[comment.UserId]
		userName := ""
		userAvatar := ""
		if user != nil {
			if comment.Anonymous == 1 {
				userName = "匿名用户"
			} else {
				userName = maskUserName(user.Nickname)
				userAvatar = oss.Cli.JoinPath(user.Avatar)
			}
		}

		// 转换标签评分
		tagRatings := make([]dto.TagRate, len(comment.TagRatings))
		for j, tag := range comment.TagRatings {
			tagRatings[j] = dto.TagRate{
				TagId:   tag.TagId,
				TagName: tag.TagName,
				Score:   tag.Score,
			}
		}

		list[i] = dto.CommentItem{
			Id:         comment.Id,
			UserId:     comment.UserId,
			UserName:   userName,
			UserAvatar: userAvatar,
			Content:    comment.Content,
			Images:     images,
			Score:      comment.Score,
			Anonymous:  comment.Anonymous,
			ReplyCount: comment.ReplyCount,
			LikeCount:  comment.LikeCount,
			TagRatings: tagRatings,
			CreateTime: comment.CreateTime,
		}
	}

	// 获取评分统计
	scoreStat, err := l.getScoreStat(req.ProductId)
	if err != nil {
		return nil, err
	}

	// 获取标签统计
	tagsStat, err := l.getTagsStat(req.ProductId)
	if err != nil {
		return nil, err
	}

	return &dto.ListCommentResp{
		Total:     count,
		List:      list,
		ScoreStat: *scoreStat,
		TagsStat:  tagsStat,
		Page:      req.Page,
		PageSize:  req.PageSize,
	}, nil
}

// maskUserName 用户名脱敏
func maskUserName(name string) string {
	if name == "" {
		return ""
	}
	nameRune := []rune(name)
	length := len(nameRune)
	if length <= 2 {
		return "*" + string(nameRune[length-1:])
	}
	return string(nameRune[0:1]) + strings.Repeat("*", length-2) + string(nameRune[length-1:])
}

// getScoreStat 获取评分统计
func (l *ProductLogic) getScoreStat(productId string) (*dto.ScoreStat, error) {
	// 获取总评价数
	totalCount, err := models.Count(l.Ctx, &models.ProductComment{}, "product_id = ? AND status = ?", productId, 1)
	if err != nil {
		return nil, err
	}

	// 获取各分数评价数
	score5Count, err := models.Count(l.Ctx, &models.ProductComment{}, "product_id = ? AND status = ? AND score = 5", productId, 1)
	if err != nil {
		return nil, err
	}
	score4Count, err := models.Count(l.Ctx, &models.ProductComment{}, "product_id = ? AND status = ? AND score = 4", productId, 1)
	if err != nil {
		return nil, err
	}
	score3Count, err := models.Count(l.Ctx, &models.ProductComment{}, "product_id = ? AND status = ? AND score = 3", productId, 1)
	if err != nil {
		return nil, err
	}
	score2Count, err := models.Count(l.Ctx, &models.ProductComment{}, "product_id = ? AND status = ? AND score = 2", productId, 1)
	if err != nil {
		return nil, err
	}
	score1Count, err := models.Count(l.Ctx, &models.ProductComment{}, "product_id = ? AND status = ? AND score = 1", productId, 1)
	if err != nil {
		return nil, err
	}

	// 计算平均分
	var avgScore float64
	if totalCount > 0 {
		avgScore = float64(score5Count*5+score4Count*4+score3Count*3+score2Count*2+score1Count) / float64(totalCount)
	}

	return &dto.ScoreStat{
		AvgScore:    avgScore,
		TotalCount:  totalCount,
		Score5Count: score5Count,
		Score4Count: score4Count,
		Score3Count: score3Count,
		Score2Count: score2Count,
		Score1Count: score1Count,
	}, nil
}

// getTagsStat 获取标签统计
func (l *ProductLogic) getTagsStat(productId string) ([]dto.TagStat, error) {
	// 获取所有评价
	var comments []*models.ProductComment
	err := models.Find(l.Ctx, &comments, "product_id = ? AND status = ?", productId, 1)
	if err != nil {
		return nil, err
	}

	// 统计每个标签的评分
	tagStatsMap := make(map[string]*tagStatInfo)
	for _, comment := range comments {
		for _, tag := range comment.TagRatings {
			info, ok := tagStatsMap[tag.TagId]
			if !ok {
				info = &tagStatInfo{
					TagId:   tag.TagId,
					TagName: tag.TagName,
				}
				tagStatsMap[tag.TagId] = info
			}
			info.TotalCount++
			info.TotalScore += tag.Score
			if tag.Score >= 4 {
				info.GoodCount++
			}
		}
	}

	// 转换为响应格式
	tagStats := make([]dto.TagStat, 0, len(tagStatsMap))
	for _, info := range tagStatsMap {
		avgScore := float64(0)
		goodRate := float64(0)
		if info.TotalCount > 0 {
			avgScore = float64(info.TotalScore) / float64(info.TotalCount)
			goodRate = float64(info.GoodCount) / float64(info.TotalCount)
		}
		tagStats = append(tagStats, dto.TagStat{
			TagId:      info.TagId,
			TagName:    info.TagName,
			AvgScore:   avgScore,
			TotalCount: info.TotalCount,
			GoodCount:  info.GoodCount,
			GoodRate:   goodRate,
		})
	}

	return tagStats, nil
}

// tagStatInfo 标签统计信息
type tagStatInfo struct {
	TagId      string
	TagName    string
	TotalCount int
	TotalScore int
	GoodCount  int
}
